package com.example.imagetest.util;

import android.webkit.MimeTypeMap;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.IOException;

import okhttp3.*;

public class UploadUtils {

    private static final String TAG = "UploadUtils";

    public static OkHttpClient createOkHttpClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor())
                .build();
    }

    public static RequestBody createMultipartBody(File file, String mimeType) {
        return new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("obj", file.getName(),
                        RequestBody.create(file, MediaType.parse(mimeType)))
                .build();
    }

    public static void logRequestDetails(String url, File file) {
        Log.d(TAG, "请求服务的url为:" + url);
        Log.d(TAG, "上传文件路径: " + file.getAbsolutePath());
        Log.d(TAG, "上传文件大小: " + file.length());
    }

    public static void handleResponse(Response response) throws IOException {
        try {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                Log.d(TAG, "文件上传成功，响应码: " + response.code());

                Gson gson = new Gson();
                JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);

                if (jsonObject.has("code") && jsonObject.get("code").getAsInt() == 1) {
                    String imageUrl = jsonObject.get("data").getAsString();
                    Log.d(TAG, "文件的访问路径: " + imageUrl);
                } else {
                    String errorMsg = jsonObject.has("msg") ? jsonObject.get("msg").getAsString() : "未知错误";
                    Log.e(TAG, "上传失败，错误信息: " + errorMsg);
                }
            } else {
                Log.e(TAG, "文件上传失败，响应码: " + response.code());
            }
        } finally {
            if (response.body() != null) {
                response.body().close(); // 关闭响应体
            }
        }
    }

    public static String getMimeType(String filePath) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
}

